package com.lebang.service;

import com.alibaba.fastjson.JSON;
import com.lebang.component.RedisClient;
import com.lebang.domain.TaskRouse;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.sys.LbbUser;
import com.lebang.example.TaskRouseExample;
import com.lebang.mapper.LbbMemberMapper;
import com.lebang.mapper.LbbUserMapper;
import com.lebang.mapper.TaskRouseMapper;
import com.lebang.model.Whether;
import com.lebangweb.common.TextUtil;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.lebang.service.DownAppService.INFO_KEY;

/**
 * @Author: hwq
 * @Date: 2020/1/3 15:38
 * @Version 1.0
 */
@Service
public class NewRouseService extends BaseService<TaskRouse, Long, TaskRouseExample> {
    private static final String KEY = "tb_task_rouse";

    @Autowired
    private RedisCacheService redisCacheService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private TaskRouseMapper rouseMapper;
    @Autowired
    private LbbMemberMapper lbbMemberMapper;
    @Autowired
    private LbbUserMapper lbbUserMapper;
    @Value("#{'${check.sdkList}'.split(',')}")
    private List<String> sdkList;
    @Value("#{'${check.account}'.split(',')}")
    private List<String> accounts;
    @Value("#{'${check.sdks}'.split(',')}")
    private List<String> sdks;

    /**
     * 获取全部数据
     *
     * @return
     */
    public List<TaskRouse> selectAll() {
        List<TaskRouse> appEatConfigs = redisCacheService.selectListByKey(KEY, TaskRouse.class);
        if (appEatConfigs == null) {
            TaskRouseExample example = new TaskRouseExample();
            example.createCriteria();
            example.setOrderByClause("weight desc");
            appEatConfigs = this.selectByExample(example);
            if (appEatConfigs != null) {
                redisCacheService.addCacheListByKey(KEY, JSON.toJSONString(appEatConfigs));
            }
        }
        return appEatConfigs;
    }

    /**
     * 获取全部启用数据
     *
     * @return
     */
    public List<TaskRouse> selectAllByEnable(RequestHeaders requestHeaders) {
        TaskRouseExample example = new TaskRouseExample();
        example.createCriteria().andEnableEqualTo(Whether.YES.getDbIndex())
                .andBrandNotLike("%"+requestHeaders.getAppStore()+"%")
                .andVersionLessThanOrEqualTo(Integer.valueOf(requestHeaders.getVersion()));
        example.setOrderByClause("weight desc");
        return this.selectByExample(example);
    }

    public void delCacheListByKey() {
        redisCacheService.delCache(KEY);
        redisCacheService.delCache(KEY + ":enable");
        redisClient.del("down_sortlist");
    }

    public void initInfo(){
        redisClient.delOne(INFO_KEY);
        List<TaskRouse> taskRouses=rouseMapper.selectByExample(null);
        taskRouses.forEach(s->{
            redisClient.hset(INFO_KEY, s.getSdkKey(), JSON.toJSONString(s));
        });
    }

    /**
     * 过滤屏蔽数据源
     * @param rouses
     * @param session
     * @return
     */
    public List<TaskRouse> checkRoot(List<TaskRouse> rouses, HttpSession session) {
        if(isRoot(session)){
            rouses=rouses.stream().filter(taskRouse -> !sdkList.contains(taskRouse.getSdkKey())).collect(Collectors.toList());
        }
        return rouses;
    }

    /**
     * 是否屏蔽用户
     * @param session
     * @return
     */
    public boolean isRoot(HttpSession session){
        String userId = (String) session.getAttribute("userid");
        if (!TextUtil.isEmpty(userId)) {
            LbbUser lbbUser = lbbUserMapper.getByUserId(userId);
            if(lbbUser!=null){
                return !accounts.contains(lbbUser.getUsername());
            }
        }
        return true;
    }

    /**
     * 检查用户每日必赚是否弹窗提示
     * @param memberId
     * @param taskRouse
     * @return
     */
    public boolean checkShow(String memberId, TaskRouse taskRouse) {
        LocalDate now = LocalDate.now();
        if(taskRouse!=null&&taskRouse.getExperienceTipSwitch()>Whether.NO.getDbIndex()){
            LocalDateTime registerTime = lbbMemberMapper.selectCreaTimeByMemberId(memberId);
            //获取今天是注册起第几天
            int days = (int) registerTime.toLocalDate().until(now, ChronoUnit.DAYS);
            //新用户
            if(days>taskRouse.getNoTipDay()){
                //老用户判断随机值
                return RandomUtils.nextInt(0,100) < taskRouse.getExperienceTipRate();
            }

        }
        return false;

    }

    /**
     * 查找所有需要屏蔽数据源的id
     * @param sdkList
     * @return
     */
    public List<Integer> selectIdBySDK(List<String> sdkList) {
        if(!TextUtil.isEmpty(sdkList)&&sdkList.size()>0){
            return rouseMapper.selectIdBySDK(sdkList);
        }
        return new ArrayList<Integer>();
    }

    /**
     * 查找第一个显示的sdk
     * @param session
     * @param rouses
     * @return
     */
    public String getFirstSdk(HttpSession session, List<TaskRouse> rouses) {
        if(isRoot(session)){
           for(TaskRouse taskRouse:rouses){
               for(String sdk:sdks){
                   if(sdk.equals(taskRouse.getSdkKey())){
                        return sdk;
                   }
               }
           }
        }
        return "all";
    }
}
